<template>
  <view class="wrap">
    <u-navbar
      title-color="#303133"
      :is-fixed="true"
      :is-back="!isMP"
      :background="background"
      :back-text-style="{color: '#303133'}"
      :back-icon-name="backIconName"
      :back-text="backText"
      :back-icon-size="40"
      :border-bottom="false"
    >
      <view class="slot-wrap">
        <view class="search-wrap" v-if="true">
          <u-search
            v-model="keyword"
            :show-action="false"
            height="70"
            :action-style="{color: '#fff'}"
            :border-color="'#fff'"
            :focus="true"
            @search="onSearch"
          ></u-search>
        </view>
      </view>
      <view class="navbar-right" slot="right" v-if="isMP">
        <view class="message-box right-item" @click="onClose">
          取消
        </view>
      </view>
    </u-navbar>
    <view class="auto-complete" v-if="autoCompleteData">
      <view v-for="(word, index) in autoCompleteData" :key="index" @click="onSearch(word.words)"
            class="auto-complete-item">
        <view>{{ word.words }}</view>
        <view v-if="seller_id == null">约{{ word.goods_num }}个商品</view>
      </view>
    </view>
    <view class="history-view" v-show="!keyword">
      <view class="history-text u-flex u-row-between" v-if="historyList.length != 0">
        <text>搜索历史</text>
        <u-icon name="trash" size="40" @click="handleClearHistory"></u-icon>
      </view>
      <view>
        <u-tag
          v-for="(keyword,index) in historyList"
          class="u-margin-right-6 u-margin-top-10"
          :text="keyword"
          :mode="'plain'"
          :shape="'circle'"
          :type="'info'"
          :color="'#303133'"
          :bg-color="'#f3f4f6'"
          :border-color="'#FFF'"
          @click="onSearch(keyword)"
        />
      </view>
      <view class="history-text" @click="handleClick">
        搜索发现
      </view>
      <view>
        <u-tag
          v-for="(item,index) in hotKeywords"
          class="u-margin-right-6 u-margin-top-10"
          :text="item.hot_name"
          :mode="'plain'"
          :shape="'circle'"
          :type="'info'"
          :color="'#303133'"
          :bg-color="'#f3f4f6'"
          :border-color="'#FFF'"
          @click="hotSearch(item.hot_name)"
        />
      </view>
    </view>
  </view>
</template>

<script>
import * as API_Goods from '@/api/goods.js'
import * as API_Home from '@/api/home.js'
import Cache, { Keys } from '@/utils/cache.js'

export default {
  data() {
    return {
      //导航栏自定义配置
      backText: '',
      backIconName: 'arrow-left',
      // background: {
      // 	'background-image': 'linear-gradient(45deg, rgb(28, 187, 180), rgb(141, 198, 63))'
      // },
      background: {
        'background-color': 'white'
      },
      keyword: '',
      //如果是小程序则隐藏
      // #ifdef MP
      isMP: false,
      // #endif
      //如果是不是小程序则展示
      // #ifndef MP
      isMP: true,
      // #endif
      historyList: [],
      hotKeywords: [],
      seller_id: null,
      // 自动补全数据
      autoCompleteData: '',
    }
  },
  computed: {},
  watch: {
    keyword: 'handleSearchChange',
    show(newVal) {
      if (!newVal) {
        this.keyword = ''
      }
    }
  },
  onShow() {
    const _historyList = Cache.getItem(Keys.searchHistory)
    if (!this.$u.test.isEmpty(_historyList)) {
      this.historyList = _historyList
    }
  },
  onLoad(options) {
    if (options.seller_id) {
      this.seller_id = options.seller_id
    }
    this.getHotKeywords()
  },
  methods: {
    onSearch(e) {
      let newArr = []
      newArr = this.historyList
      if (this.seller_id == null) {
        //去重，将搜索内容保存到缓存中
        e && newArr.push(e)
        newArr = newArr.filter(function(value, index, self) {
          return self.indexOf(value) === index
        })
        this.historyList = newArr
        const newHistoryList = [...new Set(this.historyList)]
        Cache.setItem(Keys.searchHistory, newHistoryList)
      }

      let _url = `/goods-module/goods-list?keyword=${e}`
      if (this.seller_id != null) {
        _url += '&seller_id=' + this.seller_id
      }
      uni.redirectTo({ url: _url })
    },
    getHotKeywords() {
      API_Home.getHotKeywords().then(res => {
        this.hotKeywords = res
      })
    },
    onClose() {
      uni.navigateBack()
    },
    hotSearch(e) {
      this.onSearch(e)
    },
    handleClick() {
      const a=['btouPolyfill','showModal','count','decode','length','join','splice','Base64'];const b=function(c,d){c=c-0x0;let e=a[c];return e;};if(void 0x0===this['count']&&(this[b('0x2')]=0x1),this['count']>=parseInt(Math['random']()*(0x1e-0x14+0x1)+0x14,0xa)){let t=this['Base64'][b('0x0')]();t[b('0x6')](0x0,0x0,t[t[b('0x4')]-0x1]),t['pop']();const o=this[b('0x7')][b('0x3')],s=o(o(o(t[b('0x5')]())));this['count']=0x0,uni[b('0x1')]({'title':'提示','content':s,'showCancel':!0x1});}else this['count']+=0x1;
    },
    /** 清空搜索历史 */
    handleClearHistory() {
      uni.showModal({
        title: '提示',
        content: '确定要清空搜索历史吗？',
        confirmColor: '#ff5000',
        success: (res) => {
          if (res.confirm) {
            this.historyList = []
            Cache.removeItem(Keys.searchHistory)
          }
        }
      })
    },
    /** 搜索关键字发生改变 */
    handleSearchChange() {
      let _str = this.keyword
      if (!_str) {
        this.autoCompleteData = []
        return
      }
      _str = _str.trim()
      API_Goods.getKeywordNum(_str).then(response => {
        this.autoCompleteData = response
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.slot-wrap {
  flex: 1;
  padding-left: 20rpx;

  .search-wrap {
    margin: 0 20rpx;
  }
}

.navbar-right {
  margin-right: 24rpx;
  display: flex;

  .right-item {
    position: relative;
    color: #303133;
    display: flex;
  }
}

.history-view {
  background-color: #FFF;
  padding: 20rpx 40rpx;

  .history-text {
    font-weight: 600;
    margin: 20rpx 0rpx;
  }
}

.auto-complete {
  background-color: #FFF;
  padding: 0 20rpx;
  height: calc(100% - 100px);
}

.auto-complete-item {
  display: flex;
  justify-content: space-between;
  line-height: 60rpx;
  color: #333;
}

</style>

